<template>
  <div style="width: 100vw; height: 100vh">
    <NuxtLayout name="background">
      <div class="context_box">
        <a-form ref="formRef" :model="formState" :rules="rules">
          <a-form-item label="" name="eMail">
            <a-input v-model:value="formState.eMail" placeholder="请输入邮箱">
              <template #prefix> <UserOutlined /> </template>
            </a-input>
          </a-form-item>
          <a-form-item label="" name="passWord">
            <a-input-password
              v-model:value="formState.passWord"
              placeholder="请输入密码"
            >
              <template #prefix> <LockOutlined /> </template>
            </a-input-password>
          </a-form-item>
          <a-form-item>
            <div class="login_button">
              <a-button type="primary" @click="onSubmit">登录</a-button>
              <a-button type="primary" @click="register">去注册</a-button>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </NuxtLayout>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, UnwrapRef } from "vue";
import { LoginInterfa, UserInterface } from "@/types/index";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue/lib/icons";
import { useMyFetch } from "@/utils/useMyFetch";
import { useUserInfo } from "@/store/userInfo.store";
import { message } from "ant-design-vue";

useHead({
  title: "登录",
});

const router = useRouter();

const formRef = ref();

let formState: UnwrapRef<LoginInterfa> = reactive({
  eMail: "",
  passWord: "",
});

let rules = {
  eMail: [
    {
      required: true,
      message: "邮箱不能为空",
      trigger: "blur",
    },
  ],
  passWord: [
    {
      required: true,
      message: "密码不能为空",
      trigger: "blur",
    },
  ],
};

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const body = JSON.parse(JSON.stringify(formState));
      const { data } = await useMyFetch<UserInterface>("/login", {
        method: "POST",
        body: body,
      });
      if (data) {
        const user = useUserInfo();
        let userId = useCookie("userId");
        user.setUserInfo(data);
        userId.value = data.id;
        message.success("登录成功");
        router.replace("/main");
      }
    })
    .catch((error: any) => {
      console.log("error", error);
    });
};

const register = () => {
  router.replace("/register");
};
</script>
